package util

import (
	"ChatingYourself/global"
	"ChatingYourself/pojo"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"github.com/jordan-wright/email"
	"math/rand"
	"net/smtp"
)

// MD5Encryption MD5加密
func MD5Encryption(str string) string {
	s := md5.New()
	s.Write([]byte(str))
	return hex.EncodeToString(s.Sum(nil))
}

// GetFriends 获取对应id的好友列表
func GetFriends(str string) map[string]string {
	res := make(map[string]string)
	links := &[]pojo.FriendLink{}
	err := global.DBLink.Table("friend_links").Where("account1 = ?", str).Find(&links).Error
	if err != nil {
		fmt.Println(err)
		return nil
	}
	for _, v := range *links {
		res[v.Account2] = v.Name
	}
	return res
}

// GetName 获取对应id的姓名
func GetName(id string) string {
	userInfo := pojo.UserInfo{}
	global.DBLink.Table("user_infos").Where("account = ?", id).First(&userInfo)
	return userInfo.Name
}

// GetEmail 获取对应id的Email
func GetEmail(id string) string {
	userInfo := pojo.UserInfo{}
	global.DBLink.Table("user_infos").Where("account = ?", id).First(&userInfo)
	return userInfo.Email
}

func CheckPassword(id string, newPassword string) {
	userInfo := pojo.UserInfo{}
	global.DBLink.Table("user_infos").Where("account = ?", id).First(&userInfo)
	global.DBLink.Table("user_infos").Where("account = ?", id).Model(&userInfo).Update("password", MD5Encryption(newPassword))
}

// AddFriends 添加好友
func AddFriends(account1 string, account2 string) {
	link1 := pojo.FriendLink{
		Account1: account1,
		Account2: account2,
		Name:     GetName(account2),
	}
	link2 := pojo.FriendLink{
		Account1: account2,
		Account2: account1,
		Name:     GetName(account1),
	}
	global.DBLink.Table("friend_links").Create(&link1)
	global.DBLink.Table("friend_links").Create(&link2)
}

func RandStr(n int) string {
	var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
	b := make([]rune, n)
	for i := range b {
		b[i] = letters[rand.Intn(len(letters))]
	}
	return string(b)
}

func SendEmail(toEmail string, identityStr string) {
	emailSender := email.NewEmail()
	emailSender.From = "炳源 <1634208560@qq.com>"
	emailSender.To = []string{toEmail}
	emailSender.Subject = "忘记密码"
	emailSender.HTML = []byte("您的验证码为" + identityStr)
	err := emailSender.Send("smtp.qq.com:25", smtp.PlainAuth("", "1634208560@qq.com", "wnhdcapromfoeaeb", "smtp.qq.com"))
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("send successfully ... ")
}
